/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect } from 'react';
import { Checkbox, TreeDataNode } from 'antd';
import routesConfig from '@/utils/routes.config';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import { getAuthRoute } from '@/utils/admin/menu';
import { useLocation, useSelector } from 'umi';
import { getUserInfo } from '@/services/admin/editMenu';
import { ConnectState } from '@/models/connect';

export interface RoutePermissionsItem {
  label: string;
  value: string;
}

export interface TreeDataNodeOther {
  permissions: RoutePermissionsItem[];
}

/**
 *
 * @description 组织冒泡
 * @param e
 */
function catchTap(e: any) {
  e.stopPropagation();
}

/**
 *
 * @description 扩展权限选择组件；支持多权限配置
 * @returns
 */
export function useTitleRender() {
  return (nodeData: TreeDataNode & TreeDataNodeOther) => (
    <div>
      {nodeData.title}
      {nodeData.permissions ? (
        <div onClick={catchTap}>
          {nodeData.permissions.map((item) => (
            <Checkbox value={item.value} key={item.value}>
              {item.label}
            </Checkbox>
          ))}
        </div>
      ) : null}
    </div>
  );
}

/**
 *
 * @description 过滤PermissionsCheckKeys
 * @param menu_list
 * @returns
 */
export function filterPermissionsCheckKeys(menu_list: (string | number)[]) {
  return menu_list ? menu_list.filter((item) => `${item}`.includes('-')) : [];
}

/**
 *
 * @description 拆分PermissionsKey
 * @param item
 * @returns
 */
export function splitPermissionsKey(item: any) {
  return item.split('-')[0];
}
/**
 *
 * @description 过滤父级未选中的选项
 * @param keys
 * @param parentKeys
 */
export function filterPermissionsCheckKeysByParent(
  keys: CheckboxValueType[],
  parentKeys: string[],
) {
  const parentCodes = parentKeys.map((k) => routesConfig[k]);
  return keys.filter((item) => parentCodes.includes(1 * splitPermissionsKey(item)));
}

/**
 *
 * @description 通过Permissions补充父级选中
 * @param values
 * @param checkKeys
 * @returns
 */
export function patchCheckKeysByPermissions(values: CheckboxValueType[], checkKeys: any[]) {
  const list = getAuthRoute(values.map(splitPermissionsKey));
  return [...new Set([...list, ...checkKeys])];
}

/**
 *
 * @description 权限扩展组件
 * @param props
 * @returns
 */

interface AuthorityExtendProps {
  level: string;
}
const AuthorityExtend: React.FC<AuthorityExtendProps> = (props) => {
  const { pathname } = useLocation();
  const { level } = props;
  const parentCode = routesConfig[pathname.replace('/f/', '')];
  const { currentUser } = useSelector((state: ConnectState) => state.user);
  const { userInfo } = currentUser || {};
  const { menu_list } = userInfo || {};

  if (parentCode && level && menu_list) {
    // 完整配置
    const permissions = `${parentCode}-${level}`;
    if (!menu_list.find((item) => item == permissions)) {
      // 不在权限列表，则不渲染组件内容；
      return null;
    }
  } else {
    // 加载过程中，缺少值暂不渲染组件
    return null;
  }

  return <>{props.children}</>;
};

export default AuthorityExtend;
